import axios from "axios";
import router from '@/router/index';
import Vue from 'vue';
import {
  Notification,
  Loading
} from "element-ui";
import vm from '@/main'
const _axios = axios.create();

const goLogin = () => {
  localStorage.removeItem('token');
  // 跳转登录页方法
  router.app.$router.replace({
    // path: `/login?redirect=${router.app.$route.fullPath}`,
    path: `/login`,
  });
};

_axios.interceptors.request.use(
  config => {
    // 在发送请求之前做些什么
    let myConfig = config;
    myConfig.baseURL = process.env.VUE_APP_BASE_API;
    //设置默认的请求超时时间 - 批量上传改为3分钟
    myConfig.timeout = myConfig.url=='/inf-bridge-service/back/storage/file/batchUpload'?3*60*1000: 10000 * 5;
    //设置post请求头
    myConfig.headers.post["Content-Type"] = "application/json";
    // myConfig.withCredentials = true;
    // 请求头添加token
    myConfig.headers["authorization"] = localStorage.getItem("token");
    // console.log('请求头', myConfig.data);
    return myConfig;
  },
  function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

// 添加响应拦截器
_axios.interceptors.response.use(
  response => {
    setTimeout(() => {
      vm.buttonLoading = false;
      vm.isLoading = false;
    }, 1000);
    switch (response.data.code) {
      case 200:
        return response.data.data;
        break;
      default:
        if ([401].includes(response.data.code)) {
          Notification.error({
            title: response.data.code,
            message: "登录过期",
          });
          goLogin()
        } else {
          // 文件流
          if (response.data.size) {
            return response.data;
          }
          let message = response.data.msg
          Notification.error({
            title: "error",
            message: message.length > 50 ? "业务异常，请稍后再试" : message,
            duration: 3000
          });
        }
        return Promise.reject(response.data);
        break;
    }
  },
  error => {
    if (error.response) {
      setTimeout(() => {
        vm.buttonLoading = false;
        vm.isLoading = false;
      }, 1000);
      // 对响应错误做点什么
      switch (error.response.status) {
        case 400: 
        Notification.error({
          title: "Forbidden",
          message: error.response.data.message,
        });
        break;
        case 403:
          Notification.error({
            title: "Forbidden",
            message: error.response.data.message,
          });
          break;
        case 402:
          Notification.error({
            title: "Forbidden",
            message: error.response.data.message,
          });
          break;
        case 401:
          Notification.error({
            title: "Unauthorized",
            message: "授权验证失败，请重新登录",
          });
          goLogin();
          break;
        case 405:
          Notification.error({
            title: "Method Not Allowed",
            message: "请求方式错误",
          });
          break;
        case 500:
          Notification.error({
            title: "500",
            message: "服务器开小差，请稍后重试",
          });
          break;
        default:
          break;
      }
    }
    return Promise.reject(error);
  }
);
// 下载文件
// const downloadFile = (data, name, suffix) => {
//   var raw = window.atob(data); //解码使用base-64编码字符串
//   var uInt8Array = new Uint8Array(raw.length);
//   for (var i = 0; i < raw.length; i++) {
//     uInt8Array[i] = raw.charCodeAt(i);
//   }
//   const blob = new Blob([uInt8Array], {
//     type: "application/vnd.ms-excel",
//   });
//   const url = window.URL.createObjectURL(blob);
//   const link = document.createElement("a");
//   link.style.display = "none";
//   link.href = url;
//   const fileName = name + "." + suffix;
//   link.setAttribute("download", fileName);
//   document.body.appendChild(link);
//   link.click();
//   document.body.removeChild(link);
// }
// 获取token
const getToken = async () => {
  const token = await localStorage.getItem('token')
  return token;
};
// export default axios
export default function ({
  url, // 请求地址
  data = {},
  method,
  type = 'json',
  isBlob = false,
  filename = '',
}) {
  return getToken().then(token => {
    if (!token && router.currentRoute.path !== '/login') {
      // return goLogin();
    }
    return new Promise((resolve, reject) => {
      let setting = {
        method: method || 'get',
        url,
        data,
        type,
        responseType: isBlob? 'blob': ''
      };
      vm.buttonLoading = true
      vm.isLoading = true

      _axios(setting).then(res => {
        if (isBlob) {
          // downloadFile(res, filename, '.xls')
          // var raw = window.atob(res); //解码使用base-64编码字符串
          // var uInt8Array = new Uint8Array(raw.length);
          // for (var i = 0; i < raw.length; i++) {
          //   uInt8Array[i] = raw.charCodeAt(i);
          // }
          const blob = new Blob([res], {
            type: "application/vnd.ms-excel;charset=utf-8",
          });
          const downloadElement = document.createElement('a');
          const href = window.URL.createObjectURL(blob); // 创建下载的链接
          downloadElement.href = href;
          downloadElement.download = `${filename}.xlsx`; // 下载后文件名
          document.body.appendChild(downloadElement);
          downloadElement.click(); // 点击下载
          document.body.removeChild(downloadElement); // 下载完成移除元素
          window.URL.revokeObjectURL(href); // 释放掉blob对象
          resolve();
        } else {
          resolve(res);
        }
      })
    })

  })
};
